
use strict;

open F, "<p01-input.txt" or die;     # Open the file for reading.

# Usually, <F> would fetch one line from the file.
# But we want to fetch everything. There's a trick that
# can do that. If we undefine the line separator character
# $/ then Perl would not know where to stop and read the
# full file content in one shot.

my $sep = $/;        # Save away the separator character
undef $/;            # Undefine it
my $text = <F>;      # Read the whole file
$/ = $sep;           # Restore the separator character

$text =~ tr/a-z/A-Z/;  # Capitalize all the alphabets because
                       # we will be looking for only capital letters

my $n;
for my $alphabet ('A' .. 'Z') {

    # Really, we want to use the tr operator to count the alphabets.
    # This statement
    #     $n = $text =~ tr/A/A/;
    # replaces all A's with A's and return how many chars it replaced.
    #
    # That's perfect for us.
    # But the expression gets evaluated at compile time, not at run time.
    #
    # So, this does not work
    #     $alphabet = 'A';
    #     $n = $text =~ tr/$alphabet/$alphabet/;
    #
    # We are going to have to force Perl to compile the expression
    # at runtime. We use eval to do that.
    #
    # This is how:

    my $expression = "\$n = \$text =~ tr/$alphabet/$alphabet/;";
    eval $expression;
    print "There are $n occurrences of the letter $alphabet\n";
}

__END__

Write a program that counts the number of occurrences of each letter
(from A to Z, case doesn't matter) in a text file. The output should
look similar to the following:

There are 3 occurrences of the letter A
There are 2 occurrences of the letter B
There are 1 occurrences of the letter C
There are 1 occurrences of the letter D
There are 10 occurrences of the letter E

There are 3 occurrences of the letter F
There are 1 occurrences of the letter G
There are 4 occurrences of the letter H
There are 5 occurrences of the letter I
There are 1 occurrences of the letter J
There are 1 occurrences of the letter K

There are 1 occurrences of the letter L
There are 3 occurrences of the letter M
There are 1 occurrences of the letter N
There are 8 occurrences of the letter O
There are 1 occurrences of the letter P
There are 1 occurrences of the letter Q

There are 3 occurrences of the letter R
There are 7 occurrences of the letter S
There are 10 occurrences of the letter T
There are 2 occurrences of the letter U
There are 1 occurrences of the letter V
There are 4 occurrences of the letter W

There are 1 occurrences of the letter X
There are 1 occurrences of the letter Y
There are 1 occurrences of the letter Z
Test with an input file with the following text:

The quick brown fox jumped over the lazy goose.
It was the best of times, it was the worst of times.


